package com.k7k7.sserver.client;

import com.k7k7.client.BaseClient;
import com.k7k7.db.entity.User;
import com.k7k7.util.ElementUtil;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.net.Socket;

/**
 * User: Administrator
 * Date: 2009-4-27
 * Time: 11:47:34
 */
public class ClientS extends BaseClient {
	private Element sendPac;
	public RoomOpt roomOpt;
	public FriendOpt friendsOpt;
	public UserOpt userOpt;
	public BroadCastOpt broadOpt;
	public User user;
	public boolean isReady;

	public ClientS(Socket client) throws Exception {
		super(client);
		ClientMgrS.getInstance().add(this);
		this.roomOpt = new RoomOpt(this);
		this.friendsOpt = new FriendOpt(this);
		this.userOpt = new UserOpt(this);
		this.broadOpt = new BroadCastOpt(this);
	}

	@Override
	public void handleMsg(Element root) {
		String rootName = root.getName();
		if (rootName.equals("pac")) {
			//generate back root tag
			Element _pac = (Element) root.clone();
			ElementUtil.removeAllChild(_pac);
			this.sendPac = _pac;
			//
			Element cmd = (Element) root.elements().get(0);
			String cmdtitle = cmd.attributeValue("cmd").toLowerCase();
			//
			if (cmdtitle.equals(UserCmd.scene_request_enter)) {
				roomOpt.request_enter(cmd);
			} else if (cmdtitle.equals(UserCmd.scene_entered)) {
				roomOpt.entered(cmd);
			} else if (cmdtitle.equals(UserCmd.user_getbaseinfo)) {
				this.userOpt.getInfo(cmd);
			}
		} else if (rootName.equals("msg")) {
			String msgCmd = root.attributeValue("cmd");
			if (msgCmd.equals(UserCmd.broadcast)) {
				this.broadOpt.broadcast(root);
			}
		} else if (rootName.equals("policy-file-request")) {
			//security
			try {
				this
						.send(DocumentHelper.parseText("<?xml version=\"1.0\"?>\n<cross-domain-policy>\n<site-control permitted-cross-domain-policies=\"all\"/>\n<allow-access-from domain=\"*\" to-ports=\"*\"/>\n</cross-domain-policy>\n\0").getRootElement());
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		} else {
			this.send(root);
		}
	}

	private void quit() {
		//退出所有包含此连接的集合
		this.roomOpt.quit();
		this.friendsOpt.quit();
		//todo:游戏对象,聊天对象,
		ClientMgrS.getInstance().remove(this);
	}

	@Override
	public void startError() {
		this.quit();
	}
}
